<?
   require_once("login.php");
   require_once("session.php");
   
   $app_id = "245549922176922";
   $app_secret = "fc3f6140535961c78de8e3e24fc65325";
   $my_url = "http://www.forhadahmed.net/dinty/php/facebook.php";

   SESSION();
   $code = @$_REQUEST["code"];
   
   echo "<body><table border='0' height='100%' width='100%'><tr><td valign='middle'><div align='center'><span style='font-family:arial; color:#aaaaaa; font-size:8pt;'>Loading...</span></div></td></tr></table></body><script></script>"; @flush();
   
   if(empty($code)) {
     $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
	 
     $dialog_url = "https://www.facebook.com/dialog/oauth?" 
	 . "client_id="     . $app_id 
	 . "&redirect_uri=" . urlencode($my_url)
	 . "&scope="        . "email"
	 . "&state="        . $_SESSION['state'];
	 
     echo("<script> top.location.href='" . $dialog_url . "'</script>");
   }
  
   
   if(@$_REQUEST['state'] == @$_SESSION['state']) {

     $token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id="      . $app_id 
	   . "&redirect_uri="  . urlencode($my_url)
       . "&client_secret=" . $app_secret . "&code=" . $code;

     $response = @file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);

     $graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token'];

     $user = json_decode(file_get_contents($graph_url));
	
	 login($user->id, $user->name, $params['access_token']);

	 echo(
	 "<script> top.location.href='" 
	 . "../index.php?" 
	 . "&state="
	 . $_SESSION['state']
	 . "'</script>");
   }
   else {
     echo("The state does not match. You may be a victim of CSRF.");
   }


?>